<?php
/**
 *  用户注册
*/

namespace app\api\service;

use app\api\service\Users as ServiceUsers;
use app\facade\Basic;
use app\api\model\Customer;
use app\facade\Mail;
use think\Exception;
use think\facade\Config;
use think\facade\Log;

class Register
{
    /**
     *  用户注册
    */

    public function register($param)
    {
        if(!empty($param['cusname'])){
            $where['cusname'] = $param['cusname'];
        }

        /* 验证验证码 */
        if ( !$param['code'] ) {
            return Basic::data(1,'retrieve.verificationCodeNotExist');
        }

        if ( !$code = MailCheck::check($param) ){
            return Basic::data(1,'retrieve.verificationCodeError');
        }

        if ( $param['code'] != $code ){
            return Basic::data(1,'retrieve.verificationCodeError');
        }

        if ( $param['password'] != $param['repeat_password'] ){
            return Basic::data(1,'retrieve.passwordsAreInconsistent');
        }

        $where['email'] = $param['email'];
        $result = Customer::whereOr($where)->find();

        if($result){
            return Basic::data(1,'register.accountAlreadyExists');
        }

        $password_salt = Config::get('api.password_salt');
        $create_time = date("Y-m-d H:i:s",time());
        $password = $param['password'];
        $param['password'] = md5(md5($password.$password_salt.$create_time));
        $param['create_time'] = $create_time;

        if(!isset( $param['cusname']) ||  !$param['cusname']){
            $param['cusname'] = explode('@',$param['email'])[0]??'';
        }
        # 随机取头像
        $array = [1393, 1394, 1395, 1396,1397,1398];
        $randomKey = array_rand($array); // 随机获取一个键名
        $param['avatar_id'] = $array[$randomKey]; // 根据键名取出值
        /* 默认字段 */
        $param['is_login'] = 2;
        $param['login_status'] = 1;
        $param['source'] = 2; // 来源：2 网站
        $param['is_advance'] = 0;

        $result = Customer::create($param);

        /* 保存登录信息 */
        $token = new Token();
        $token = $token->get($result);

        /* 更新登陆信息 */
        $result->login_num = ($result->login_num + 1);

        $result->save();


        $serviceRetrieve = new ServiceUsers();
        $userinfo = $serviceRetrieve->userinfo($result);

        $userinfo =[
            'token' => $token,
            'expire_in' => config('api.token_expire_in'),
            'role' => $result->role,
            'userinfo' => $userinfo
        ];
        try {

            $result = Mail::send('register',$param['email']);
            Log::INFO("注册发邮件: {$param['email']} :".json_encode($result));
        } catch (Exception $e) {
            Log::error('注册发邮件失败:'.json_encode($e->getMessage()));
        }

        return Basic::data(0,'login.loginSuccessful',$userinfo);
    }


    /**
     *  获取邮箱验证
     */
    public function getEmailCode($param)
    {

        $result = Customer::where('email',$param['email'])->find();

        if($result){
            return Basic::data(1,'register.emailAlreadyExists');
        }

        $data['code'] = getVerifyCode(6);
        $data['to'] = $param['email'];
        $data['subject'] = 'get Register Email Code';
        $content = <<<HTML
     code: {$data['code']}
HTML;
        $data['content'] = $content;
        return MailCheck::create($data);
    }


}
